package com.atguigu.shangrongbao.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.JwtUtils;
import com.atguigu.common.util.MD5;
import com.atguigu.shangrongbao.core.mapper.UserAccountMapper;
import com.atguigu.shangrongbao.core.mapper.UserLoginRecordMapper;
import com.atguigu.shangrongbao.core.pojo.entity.UserAccount;
import com.atguigu.shangrongbao.core.pojo.entity.UserInfo;
import com.atguigu.shangrongbao.core.mapper.UserInfoMapper;
import com.atguigu.shangrongbao.core.pojo.entity.UserLoginRecord;
import com.atguigu.shangrongbao.core.pojo.vo.LoginVo;
import com.atguigu.shangrongbao.core.pojo.vo.RegisterVo;
import com.atguigu.shangrongbao.core.pojo.vo.UserInfoVO;
import com.atguigu.shangrongbao.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author Author
 * @since 2021-08-10
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVo registerVo) {
    //    首先要查询当前手机号是否已经存在（已注册）
        String mobile = registerVo.getMobile();
        Integer count = baseMapper.selectCount(new QueryWrapper<UserInfo>().eq("mobile", mobile));
        //如果count==0，isTrue内部进行了取反
        Assert.isTrue(count==0, ResponseEnum.MOBILE_EXIST_ERROR);
        //信息封装
        UserInfo userInfo = new UserInfo();
        userInfo.setMobile(mobile);
        //默认用户名为mobile
        userInfo.setName(mobile);
        userInfo.setNickName(mobile);
        userInfo.setUserType(registerVo.getUserType());
        //密码需要加密
        userInfo.setPassword(MD5.encrypt(registerVo.getPassword()));
        //头像，注册可以使用一个默认头像
        userInfo.setHeadImg(UserInfo.USER_AVATAR);
        //默认状态：1正常，0锁定
        userInfo.setStatus(1);
        // 注册

        baseMapper.insert(userInfo);

        //账户表中存入user
        UserAccount userAccount = new UserAccount();
        //账户关联用户
        userAccount.setUserId(userInfo.getId());
        userAccountMapper.insert(userAccount);
    }

    @Override
    public UserInfoVO login(LoginVo loginVo) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        Integer userType = loginVo.getUserType();
        //查询用户是否存在
        // this.getOne(new QueryWrapper<>().eq(UserInfo::getUserType, userType))  双冒号语法只支持lambada

        // baseMapper.
        // baseMapper.selectOne(new QueryWrapper<>().eq("mobile", mobile).eq("user_type", userType))
        // UserInfo userInfo = baseMapper.selectOne(Wrappers.lambdaQuery().eq(UserInfo::getMobile, mobile).eq(UserInfo::getUserType, userType));
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.eq(UserInfo::getMobile, mobile).eq(UserInfo::getUserType, userType);
        UserInfo userInfo = baseMapper.selectOne(lambdaQueryWrapper);
        //泛型是给lambdaQuery的
        // baseMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getMobile, mobile).eq(UserInfo::getUserType, userType))


        //用户不存在
        Assert.isNotNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        //校验密码 断言相等，不等则抛出异常
        Assert.equals(MD5.encrypt(password), userInfo.getPassword(), ResponseEnum.LOGIN_PASSWORD_ERROR);
        //用户是否被禁用
        // Assert.isTrue(userInfo.getStatus() == 0,ResponseEnum.LOGIN_LOKED_ERROR);
        Assert.notEquals(userInfo.getStatus(), 0, ResponseEnum.LOGIN_LOKED_ERROR);
        log.info("登录信息：{}", loginVo);
        //记录登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        //插入记录
        userLoginRecordMapper.insert(userLoginRecord);
        //生成token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        log.info("生成的token:{}", token);

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setHeadImg(userInfo.getHeadImg());
        userInfoVO.setMobile(userInfo.getMobile());
        userInfoVO.setName(userInfo.getName());
        userInfoVO.setNickname(userInfo.getNickName());
        userInfoVO.setUserType(userInfo.getUserType());
        userInfoVO.setToken(token);

        return userInfoVO;
    }

    @Override
    public Boolean checkMobile(String mobile) {
        //查询手机号是否存在
        Integer count = baseMapper.selectCount(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getMobile, mobile));
        return count > 0;
    }

}
